class ListNode{
    public int val;
    public ListNode next;

    public ListNode() {}

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    public ListNode addTwoNumbers(ListNode l1,ListNode l2){
        ListNode cur1 = l1,cur2 = l2;
        ListNode newHead = new ListNode(0);//虚拟头节点
        ListNode prev = newHead;//方便尾插
        int t = 0;//记录进位
        while(cur1 != null || cur2 != null || t != 0){

            //先加第一个链表
            if(cur1 != null){
                t += cur1.val;
                cur1 = cur1.next;
            }

            //再加第二个链表
            if(cur2 != null){
                t += cur2.val;
                cur2 = cur2.next;
            }

            prev.next = new ListNode(t % 10);
            prev = prev.next;
            t /= 10;
        }
        return newHead.next;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        ListNode l1Node1 = new ListNode(2);
        ListNode l1Node2 = new ListNode(4);
        ListNode l1Node3 = new ListNode(3);
        l1Node1.next = l1Node2;
        l1Node2.next = l1Node3;

        ListNode l2Node1 = new ListNode(5);
        ListNode l2Node2 = new ListNode(6);
        ListNode l2Node3 = new ListNode(4);
        l2Node1.next = l2Node2;
        l2Node2.next = l2Node3;

        ListNode newList = solution.addTwoNumbers(l1Node1,l2Node1);
        ListNode cur = newList;

        while(cur != null){
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
    }
}